const process = window.require("child_process")
const { spawn } = window.require('child_process');
const fs      = window.require("fs")
const path = window.require('path')
import {dls} from './local-store'
class FrpControl{
    file = path.join(path.dirname(dls.getDir()),'frpc.ini')
    logFile =  path.join(path.dirname(dls.getDir()),'/log/frpc.txt')
    tail = path.join(path.dirname(dls.getDir()),'tail.exe')
    main = dls.getDir()
    taskName = `frpc.exe`
    exec(cmd){
        process.exec(cmd,(error, stdout, stderr) => {
            if(error)
                console.log("error:"+error);
            console.log("stdout:"+stdout);
            if(stderr)
                console.log("stderr:"+stderr);
        })  
    }
    readSync(f = this.file){
        let data = fs.readFileSync(f).toString();
        return data
    }
    read(fn,f = this.file){
        fs.readFile(f,"utf-8",fn)
    }
    write(content,fn,f = this.file){
        fs.writeFile(f,content,fn)
    }
    runSpawn(fn,file = this.file){
        // process.exec(`cmd /c F:\\goto\\内网穿透\\frp_0.30.0_windows_amd64\\frpc.exe -c ${file}`,fn)
        const frpc = spawn("cmd",["/c",this.main,"-c",file])
        frpc.stdout.on('data',(data)=>{
            console.log(data.toString())
        })
        // fn()
    }
    run(fn,file = this.file){
        process.exec(`cmd /c start /b ${this.main} -c ${file}`,fn)
    }
    stop(fn,task = this.taskName){
        process.exec(`cmd /c taskkill /f /t /im  ${task}`,fn)
    }
    search(fn,n = this.taskName){
        process.exec(`cmd /c tasklist | findstr ${n}`,fn)
    }

    //日志
    logSpawn(fn,file = this.logFile){
        // process.exec(`cmd /c F:\\goto\\内网穿透\\frp_0.30.0_windows_amd64\\frpc.exe -c ${file}`,fn)
        const log = spawn("cmd",["/c",this.tail,"-f",file])
        log.stdout.on('data',(data)=>{
            fn(data)
            console.log(data.toString())
        })
        log.exit = ()=>{process.exec(`cmd /c taskkill /f /t /im  tail.exe`,(a,b,c)=>{})}
        return log
    }
}
const fc = new FrpControl()
export {FrpControl,fc}
